import Router from '@koa/router'
import User from '../models/User'
import { omit } from 'lodash'
import { Model, Op } from 'sequelize'
import Article from '../models/Article'
import BigModelConfig from '../models/BigModelConfig'
import SiteConfig from '../models/SiteConfig'
import { updateRuntimeConfigFromDB } from '../configs/runtimeConfig'
import TeachCase from '../models/TeachCase'

const modelsMap = {
    users: User,
    articles: Article,
    // bigModelConfigs: BigModelConfig,
    // siteConfigs: SiteConfig,
    teachCases: TeachCase,
}

// 把前端的dbInclude参数换成sequelize的include参数
const getDbInclude = (dbInclude: any[]) => {
    return dbInclude.map((item) => {
        console.log(item)
        if (typeof item === 'string') {
            return {
                model: modelsMap[item as keyof typeof modelsMap],
            }
        }

        return {
            ...item,
            model: modelsMap[item.model as keyof typeof modelsMap],
        }
    })
}

export const getHotList: Router.Middleware = async (ctx) => {
    const { modelName } = ctx.params as {
        modelName: keyof typeof modelsMap
    }

    const model = modelsMap[modelName]

    if (!model) {
        ctx.body = { success: false, msg: '参数错误' }
        return
    }

    const { page = 1, pageSize = 10 } = ctx.request.body as {
        page: string
        pageSize: string
    }

    const query = omit(ctx.request.body, [
        'page',
        'pageSize',
        'password',
        'dbInclude',
        'attributes',
    ])
    const dbInclude = getDbInclude(ctx.request.body.dbInclude)

    // 选择属性
    const attributes: any = { exclude: ['password', 'deleteAt'] }
    if (ctx.request.body.attributes) {
        const bodyAttributes = ctx.request.body.attributes
        if (bodyAttributes.include) {
            attributes.include = bodyAttributes.include
        }
        if (bodyAttributes.exclude) {
            bodyAttributes.exclude.push('password', 'deleteAt')
            attributes.exclude = bodyAttributes.exclude
        }
    }

    console.log(dbInclude)

    const where: any = {}

    if (query['id']) {
        where.id = query['id']
    } else {
        for (const key in query) {
            if (query[key]) {
                where[key] = {
                    [Op.like]: `%${query[key]}%`,
                }
            }
        }
    }

    console.log(where)

    try {

        // @ts-ignore
        const list = await model.findAndCountAll({
            where,
            attributes,
            limit: +pageSize,
            offset: (+page - 1) * +pageSize,
            order: [['viewCount', 'DESC']],
            include: dbInclude,
        })
        ctx.body = { success: true, data: list }
    } catch (error) {
        console.log(error)
        ctx.body = { success: false, msg: '获取列表失败' }
    }
    // ctx.body = { success: false, msg: '获取列表失败' }
}
export const del: Router.Middleware = async (ctx) => {
    const { modelName, id } = ctx.params

    const model = modelsMap[modelName as keyof typeof modelsMap]

    if (!model || !id) {
        ctx.body = { success: false, msg: '参数错误' }
        return
    }

    try {
        // @ts-ignore
        const list = await model.destroy({
            where: { id },
        })
        ctx.body = { success: true, data: list }
    } catch (error) {
        ctx.body = { success: false, msg: '删除失败' }
    }
}
export const update: Router.Middleware = async (ctx) => {
    const { modelName, id } = ctx.params

    const model = modelsMap[modelName as keyof typeof modelsMap]

    if (!model) {
        ctx.body = { success: false, msg: '参数错误' }
        return
    }

    const data = ctx.request.body

    try {
        const newData = { ...data, id }
        // @ts-ignore
        const list = await model.update(newData, {
            where: { id },
        })
        if (modelName === 'siteConfigs') {
            updateRuntimeConfigFromDB()
        }
        ctx.body = { success: true, data: list }
    } catch (error) {
        ctx.body = { success: false, msg: '更新失败' }
    }
}
export const add: Router.Middleware = async (ctx) => {
    const { modelName } = ctx.params

    const model = modelsMap[modelName as keyof typeof modelsMap]

    if (!model) {
        ctx.body = { success: false, msg: '参数错误' }
        return
    }

    const data = ctx.request.body

    try {
        // @ts-ignore
        const list = await model.create(data)
        ctx.body = { success: true, data: list }
    } catch (error) {
        console.log(error)
        ctx.body = { success: false, msg: '添加失败' }
    }
}

export const getDict: Router.Middleware = async (ctx) => {
    const { modelName } = ctx.params

    const model = modelsMap[modelName as keyof typeof modelsMap]

    if (!model) {
        ctx.body = { success: false, msg: '参数错误' }
        return
    }

    const { labelProp = 'id', valueProp = 'id' } = ctx.request.query as {
        labelProp?: string
        valueProp?: string
    }

    try {
        // @ts-ignore
        const list = await model.findAll({
            attributes: {
                include: [valueProp, labelProp],
                exclude: ['password', 'deleteAt'],
            },

            order: [['createdAt', 'DESC']],
        })
        const result = list.map((item) => {
            return {
                label: item.get(labelProp),
                value: item.get(valueProp),
            }
        })
        ctx.body = result
    } catch (error) {
        console.log(error)
        ctx.body = { success: false, msg: '获取列表失败' }
    }
    // ctx.body = { success: false, msg: '获取列表失败' }
}
